using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using OpenQuarters.WebQuarters.Utils;
using System.Text;
using OpenQuarters.WebQuarters.Core;

namespace OpenQuarters.WebQuarters.Core.Web.Areas.CMS.Controllers
{
    public class AccountController : Controller
    {
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login()
        {
            var formResponse = new Core.JFormResponse<Core.User>();

            var username = Request.Form["Username"];
            var password = Request.Form["Password"];

            if (username == null || username.Length == 0)
            {
                formResponse.errorMessages[""].Add(Core.Translation.Translate("Please_enter_your_username"));
            }
            if (password == null || password.Length == 0)
            {
                formResponse.errorMessages[""].Add(Core.Translation.Translate("Please_enter_your_password"));
            }

            if (formResponse.errorMessages.Count == 0)
            {
                // TODO: Count login attempts, disable account after x failed attempts
                if (Core.User.Current.Login(username, password))
                {
                    // TODO: Reset login attempts to 0
                    formResponse.result = Core.User.Current;
                    if (!string.IsNullOrEmpty(Request["ReturnUrl"]))
                        return Redirect(Server.UrlDecode(Request["ReturnUrl"]));
                    else
                        Core.User.Current.LastFailedURL = "";

                }
                else
                {
                    formResponse.errorMessages[""].Add(Core.Translation.Translate("The_details_provided_are_not_valid,_please_try_again"));
                }
            }

            return formResponse.Return();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Logout()
        {
            Core.User.Current.Logout();
            return Redirect(Request["Redirect"] == null ? Request["ReturnUrl"] == null ? "/" : Request["ReturnUrl"] : Request["Redirect"]);
        }

        public ActionResult VerifyUser()
        {
            JFormResponse<DefaultJFormClass> response = new JFormResponse<DefaultJFormClass>();

            if (!string.IsNullOrEmpty(Request["uid"]) && !string.IsNullOrEmpty(Request["vc"]))
            {
                var user = OpenQuarters.WebQuarters.Core.User.Table.Where(u => u.UserId == Request["uid"] && u.VerificationCode == Request["vc"]).FirstOrDefault();

                if (user != null)
                {
                    user.IsActive = true;
                    user.Save();
                    response.messages.Add("verification", new List<string>() { "Your account has been verified" });
                    JFormResponse<DefaultJFormClass>.Current = response;
                    return Redirect(Request.Form["Redirect"] == null ? "/site/" + CMSPage.LoginPage.Urls[0].PageUrl : Request.Form["Redirect"]);
                }
            }

            response.errorMessages.Add("verification", new List<string>() { "Please check the verification code is correct" });
            JFormResponse<DefaultJFormClass>.Current = response;
            return Redirect("/site/" + CMSPage.LoginPage.Urls[0].PageUrl);
        }


        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult HasPermission()
        {
            ViewData.Model = Core.User.Current.HasPermission(Request.Form["Permission"], Request.Form["Value"]).ToJSON();
            return View(Site.Helpers.SharedView.Service);
        }



        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetMessageCount(string id)
        {
            // id is message type
            var messages = Core.User.Current.UserMessages.Where(e => e.UserId == Core.User.Current.UserId && !e.Read && (id == null || id.Length == 0 || e.Category == id)).ToList();
            var currentPermissions = Core.User.Current.AllPermissions;
            var currentWorkflowItems = WorkflowItem.OpenItems;

            foreach (var w in currentWorkflowItems)
            {
                if (messages.FirstOrDefault(e => e.WorkflowItemId == w.WorkflowItemId) == null && currentPermissions.FirstOrDefault(e => e.Name == w.RequiredPermissionName && e.Value == w.RequiredPermissionValue) != null)
                {
                    messages.Add(new UserMessage()
                    {
                        UserId = Core.User.Current.UserId,
                        Tags = "",
                        Body = "",
                        From = "admin",
                        FromName = "System",
                        Subject = w.ToString(),
                        Category = "Admin",
                        WorkflowItem = w
                    }.Save());
                }
            }

            ViewData.Model = messages.Count.ToString();
            return View(Site.Helpers.SharedView.Service);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetMessages(string id)
        {
            // id is message type
            var messages = Core.User.Current.UserMessages.Where(e => e.UserId == Core.User.Current.UserId && !e.Read && (id == null || id.Length == 0 || e.Category == id)).OrderByDescending(e => e.DateCreated).ToList();

            if (messages.Count == 0)
            {
                messages = Core.User.Current.UserMessages.Where(e => e.UserId == Core.User.Current.UserId && (id == null || id.Length == 0 || e.Category == id)).OrderByDescending(e => e.DateCreated).Take(10).ToList();
            }
            else if (messages.Count < 10)
            {
                messages.AddRange(Core.User.Current.UserMessages.Where(e => e.UserId == Core.User.Current.UserId && e.Read && (id == null || id.Length == 0 || e.Category == id)).OrderByDescending(e => e.DateCreated).Take(10 - messages.Count).ToList());
            }
            else
            {
                messages.RemoveAll((UserMessage e) => e.Read);
            }

            ViewData.Model = messages.ToJSON();
            return View(Site.Helpers.SharedView.Service);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult MarkMessageAsRead(string id)
        {
            // id is message id
            var msg = Core.UserMessage.Table.FirstOrDefault(e => e.MessageId == id.ToInt64() && e.UserId == Core.User.Current.UserId);
            if (msg != null)
            {
                msg.Read = true;
                msg.Save();
            }
            ViewData.Model = "{}";
            return View(Site.Helpers.SharedView.Service);
        }
    }
}